<template>
  <div class="container">
    <div class="header">
      <el-card>
        <el-row
          :gutter="20"
          style="
            height: 110px;
            display: flex;
            justify-content: center;
            align-items: center;
          "
        >
          <el-col :span="1">
            <el-avatar shape="square" :size="70"></el-avatar>
          </el-col>
          <el-col :span="16" style="margin-left: 15px">
            <h1 style="font-weight: normal; color: #409eff">
              {{ roleInfo.roleName }}
            </h1>
            <p style="color: #999999; font-size: 12px; line-height: 30px">
              {{ roleInfo.remark ? roleInfo.remark : "暂无相关描述" }}
            </p>
          </el-col>
          <el-col :span="6" style="text-align: right" class="btn">
            <el-button @click="openStatus">设置状态</el-button>
            <el-button @click="openDateScope">设置数据权限</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <el-card style="margin-top: 8px; position: relative">
      <div class="close">
        <el-button
          style="font-size: 28px"
          type="text"
          icon="el-icon-close"
          @click="$emit('closePermission')"
        ></el-button>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="操作权限" name="authorization">
          <MenuList
            :queryRoleId="roleInfo.roleId"
            :listType="'role'"
            :header="false"
            :height="458"
            ref="menuListRef"
          ></MenuList>
          <el-button type="primary" @click="saveRoleMenu" style="color: #fff"
            >保 存</el-button
          >
        </el-tab-pane>
        <el-tab-pane label="人员列表" name="userList">
          <RoleUserList :queryRoleId="roleInfo.roleId"></RoleUserList>
        </el-tab-pane>
        <el-tab-pane label="操作日志" name="operLog">
          <OperLog
            :header="false"
            :listType="'role'"
            :queryParams="{ roleId: roleInfo.roleId }"
          ></OperLog>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      title="设置角色状态"
      :visible.sync="statusDialogVisible"
      :before-close="() => (statusDialogVisible = false)"
      width="20%"
    >
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="角色名称：">
          <el-input v-model="statusForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="权限字符：">
          <el-input v-model="statusForm.roleKey" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色状态：">
          <el-radio-group v-model="statusForm.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveStatus()">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="分配数据权限"
      :visible.sync="dataScopeDialogVisible"
      :before-close="() => (dataScopeDialogVisible = false)"
      width="500px"
    >
      <el-form ref="form" :model="dataScopeForm" label-width="100px">
        <el-form-item label="角色名称：">
          <el-input v-model="dataScopeForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称：">
          <el-input v-model="dataScopeForm.roleKey" disabled></el-input>
        </el-form-item>
        <el-form-item label="权限范围：">
          <el-select
            v-model="dataScopeForm.dataScope"
            style="width: 220px"
            placeholder="请选择数据范围"
          >
            <el-option
              v-for="dict in dict.type.sys_role_data_scope"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限：" v-show="dataScopeForm.dataScope == 2">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand"
            >展开/折叠</el-checkbox
          >
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll"
            >全选/全不选</el-checkbox
          >
          <el-checkbox v-model="deptCheckStrictly">父子联动</el-checkbox>
          <div class="deptTree">
            <el-tree
              class="tree-border"
              show-checkbox
              :data="deptTree"
              node-key="id"
              :check-strictly="!deptCheckStrictly"
              ref="deptTree"
              default-expand-all
              :props="defaultProps"
              empty-text="加载中，请稍候"
            ></el-tree>
          </div>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dataScopeDialogVisible = false" :loading="loading"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleDateScopeSave">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TableWrapper from "@/components/Table/TableWrapper.vue";
import MenuList from "@/views/system/menu/index.vue";
import RoleUserList from "./RoleUserList.vue";
import OperLog from "@/views/system/operlog/index.vue";
import {
  setMenuAuth,
  updateRoleStatus,
  getRolDateScope,
  setRolDateScope,
} from "@/api/system/role.js";
import { getDeptTree } from "@/api/system/dept.js";

export default {
  components: { TableWrapper, MenuList, RoleUserList, OperLog },
  dicts: ["sys_normal_disable", "sys_role_data_scope"],
  props: {
    roleInfo: {
      require: true,
      type: Object,
    },
  },
  data() {
    return {
      activeName: "authorization",
      statusDialogVisible: false,
      dataScopeDialogVisible: false,
      statusForm: {},
      dataScopeForm: {},
      deptExpand: true,
      deptNodeAll: false,
      deptCheckStrictly: false,
      deptTree: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      loading: false,
    };
  },
  methods: {
    handleClick() {},
    // 保存角色菜单
    saveRoleMenu() {
      const ids = this.$refs.menuListRef.selectionList.map(
        (item) => item.menuId
      );
      if (this.roleInfo.roleId != 0) {
        setMenuAuth(this.roleInfo.roleId, ids).then((res) => {
          // 重新渲染菜单
          this.$modal.msgSuccess(res.msg);
          this.$refs.menuListRef.refreshChange();
        });
      }
    },
    openStatus() {
      this.statusForm = {
        roleName: this.roleInfo.roleName,
        roleKey: this.roleInfo.roleKey,
        status: this.roleInfo.status,
      };

      this.statusDialogVisible = true;
    },
    handleSaveStatus() {
      updateRoleStatus(this.roleInfo.roleId, this.statusForm.status).then(
        (res) => {
          // 关闭弹框
          this.statusDialogVisible = false;
          // 通知列表刷新
          this.$emit("refresh", this.statusForm.status);
        }
      );
    },
    openDateScope() {
      // 查询部门树
      if (this.deptTree.length == 0) {
        getDeptTree().then((res) => {
          this.deptTree = res.data;
        });
      }
      getRolDateScope(this.roleInfo.roleId).then((res) => {
        // 缓存结果，避免重复查询
        this.dataScopeForm = res.data;
        this.dataScopeDialogVisible = true;

        // 使用响应式数据绑定更新界面
        this.$nextTick(() => {
          if (res.data.deptIds) {
            // 使用map函数转换数据，避免直接操作DOM
            const deptIds = res.data.deptIds.map((v) => ({ id: v }));
            // 使用数据绑定更新组件状态
            this.$refs.deptTree.setCheckedNodes(deptIds);
          }
        });
      });
    },
    handleCheckedTreeExpand() {
      for (const item in this.$refs.deptTree.store.nodesMap) {
        this.$refs.deptTree.store.nodesMap[item].expanded = this.deptExpand;
      }
    },
    handleCheckedTreeNodeAll() {
      const deptOptions = [];
      for (const item in this.$refs.deptTree.store.nodesMap) {
        deptOptions.push({ id: item });
      }

      this.$refs.deptTree.setCheckedNodes(this.deptNodeAll ? deptOptions : []);
    },
    handleDateScopeSave() {
      // 获取所有被选中的数据
      const deptIds = this.$refs.deptTree.getCheckedKeys();
      this.dataScopeForm.deptIds = deptIds;
      setRolDateScope(this.dataScopeForm).then((res) => {
        this.loading = false;
        this.dataScopeDialogVisible = false;
        this.$modal.msgSuccess(res.msg);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  ::v-deep .el-card {
    .el-card__body {
      padding: 0 !important;
    }
  }

  ::v-deep .el-col {
    .el-button {
      color: #999999;
    }
  }
}

.deptTree {
  ::v-deep .tree-border {
    border: 1px solid rgba(204, 204, 204, 0.5);
  }
}
.close {
  position: absolute;
  right: 30px;
  top: 15px;
  z-index: 1;
  font-size: 25px;
}
</style>